package com.api.controller;

import com.api.common.BaseResponse;
import com.api.common.ResultUtils;
import com.api.mapper.InterfaceInfoMapper;
import com.api.mapper.UserInterfaceInfoMapper;
import com.api.model.vo.InterfaceInfoVo;
import com.apicommon.model.entity.InterfaceInfo;
import com.apicommon.model.entity.UserInterfaceInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author tianzhou
 */
@RestController
@RequestMapping("/analysis")
@Slf4j
public class AnalysisController {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private InterfaceInfoMapper interfaceInfoMapper;

    /**
     * description 统计各接口调用情况
     *
     * @return com.api.common.BaseResponse<java.util.List<com.api.model.vo.InterfaceInfoVo>>
     * @title topInvokeInterface
     * @author tianzhou
     * @date 2023/3/30 16:28
     */
    @GetMapping("/top-invoke")
    public BaseResponse<List<InterfaceInfoVo>> topInvokeInterface() {
        List<UserInterfaceInfo> userInterfaceInfoList = userInterfaceInfoMapper.listInvokeInterInfo(3);
        Map<Long, List<UserInterfaceInfo>> userInterfaceInfoMap = userInterfaceInfoList.stream().
                collect(Collectors.groupingBy(UserInterfaceInfo::getInterfaceInfoId));

        QueryWrapper<InterfaceInfo> interfaceInfoQueryWrapper = new QueryWrapper<>();
        interfaceInfoQueryWrapper.in("id", userInterfaceInfoMap.keySet());
        List<InterfaceInfo> interfaceInfoList = interfaceInfoMapper.selectList(interfaceInfoQueryWrapper);

        List<InterfaceInfoVo> interfaceInfoVoList = interfaceInfoList.stream().map(interfaceInfo -> {
            InterfaceInfoVo interfaceInfoVo = new InterfaceInfoVo();
            BeanUtils.copyProperties(interfaceInfo, interfaceInfoVo);
            Integer totalNum = userInterfaceInfoMap.get(interfaceInfo.getId()).get(0).getTotalNum();
            interfaceInfoVo.setTotalNum(totalNum);
            return interfaceInfoVo;
        }).collect(Collectors.toList());

        return ResultUtils.success(interfaceInfoVoList);
    }

}
